package org.seckill.service.impl;

import org.seckill.dao.SeckillDao;
import org.seckill.dao.SuccessKilledDao;
import org.seckill.dao.cache.RedisDao;
import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExecution;
import org.seckill.entity.Seckill;
import org.seckill.entity.SuccessKilled;
import org.seckill.enums.SeckillStatEnum;
import org.seckill.exception.RepeatKillException;
import org.seckill.exception.SeckillCloseException;
import org.seckill.exception.SeckillException;
import org.seckill.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

/**
 * 秒杀Service实现类
 *
 * @author Simple
 * @create 2017-02-10 14:14
 **/
@Service
public class SeckillServiceImpl implements SeckillService{

    @Autowired
    SeckillDao seckillDao;
    @Autowired
    SuccessKilledDao successKilledDao;
    @Autowired
    RedisDao redisDao;

    Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 盐值加密
     */
    public final String slat = "123";

    @Override
    public List<Seckill> getSeckillList() {
        return seckillDao.queryAll(0,10);
    }

    @Override
    public Seckill getById(long seckillId) {
        return seckillDao.queryById(seckillId);
    }

    @Override
    public Exposer exportSeckillUrl(long seckillId) {
        //简单优化:redis缓存下来,超时的基础上维护一致性
        /**
         * get from cache
         * if null
         *  get db
         * else
         *  put cache
         *  locgoin
         */
        Seckill seckill = redisDao.getSeckill(seckillId);
        if (seckill == null){
            seckill = seckillDao.queryById(seckillId);
            if (seckill == null){
                return new Exposer(false, seckillId);
            }else {
                redisDao.putSeckill(seckill);
            }
        }
        if(seckill == null){
            return new Exposer(false,seckillId);
        }
        Date nowDate = new Date();
        if(nowDate.getTime() < seckill.getStartTime().getTime() || nowDate.getTime() >seckill.getEndTime().getTime()){
            //不在秒杀的时间段内
            return new Exposer(false,seckillId,nowDate.getTime(),seckill.getStartTime().getTime(),seckill.getEndTime().getTime());
        }
        String md5 = getMD5(seckillId);
        return new Exposer(true,md5,seckillId);
    }
    public String getMD5(long seckillId){
        String basemd5 = seckillId + "/" + slat;
        String md5 = DigestUtils.md5DigestAsHex(basemd5.getBytes());
        return md5;
    }
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5) throws SeckillException, RepeatKillException, SeckillCloseException {
        if(md5 == null || !getMD5(seckillId).equals(md5)){
            throw new SeckillException("seckill data rewrite!");
        }
        Date now = new Date();
        try {
            int reduceNum = seckillDao.reduceNumber(seckillId,now);
            if(reduceNum <= 0){
                //没有更新记录表
                throw new SeckillCloseException("seckill is close!");
            }else{
                int insertNum = successKilledDao.insertSuccessKilled(seckillId,userPhone);
                if(insertNum <= 0){
                    //重复秒杀
                    throw new RepeatKillException("Seckill Repeated!");
                }else{
                    //秒杀成功
                    SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId,userPhone);
                    return new SeckillExecution(seckillId, SeckillStatEnum.SUCCESS,successKilled);
                }
            }
        } catch (SeckillCloseException e) {
            throw e;
        } catch (RepeatKillException e) {
            throw e;
        } catch (Exception e){
            logger.error(e.getMessage(),e);
            throw new SeckillException("seckill inner error : "
                    + e.getMessage());
        }
    }
}